import cv2
import numpy as np
from Models.ImageProcess import MyCV2 as imp
from R_image_matching_main.risgmatching_sift import RSIFTMatcher,add_ones
import time
#程序中链接了多个 OpenMP 运行时库的副本
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def find_corners(image_path):
    '''

    :param image_path:
    :return: corners(左上，右下，列行)
    '''
    # 读取图像
    img = cv2.imread(image_path)
    if img is None:
        print("Error: Image not found.")
        return

        # 转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 应用阈值处理
    _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)

    # 寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 假设最大的轮廓是主体内容
    if contours:
        max_contour = max(contours, key=cv2.contourArea)

        # 轮廓的边界点（近似为角点）
        # 这里我们直接使用轮廓的边界点，但在实际情况中可能需要更复杂的算法来定义角点
        peri = cv2.arcLength(max_contour, True)
        approx = cv2.approxPolyDP(max_contour, 0.04 * peri, True)

        # 角点坐标(左上，左下，右下，右上)列行
        corners = approx.reshape((-1, 2))
        # corners = max_contour.reshape((-1, 2))
        y_min = np.min(corners[:,0])
        y_min_index = np.where(corners[:,0]==y_min)[0]
        x_min = np.min(corners[y_min_index,1])
        left_top = np.array([y_min,x_min]).reshape(1,2)
        y_max = np.max(corners[:,0])
        y_max_index = np.where(corners[:, 0] == y_max)[0]
        x_max = np.max(corners[y_max_index,1])
        right_down = np.array([y_max,x_max]).reshape(-1,2)
        corners = np.concatenate([left_top,right_down],axis=0)
        return corners


        # 使用图像路径调用函数

if __name__ == '__main__':
    risg = RSIFTMatcher()
    img0 = cv2.imread(r"D:\DownloadCache\base_map\4.TIF")
    img1 = cv2.imread(r"D:\DownloadCache\4_2013_2855_2513_3655.TIF")

    if (img0 is None) or (img1 is None):
        print('Error: Image file not found.')
        exit()
    start_time = time.perf_counter()
    mkpts0, mkpts1, conf, main_dir,Mat = risg.match(img0, img1, nrotate=5)
    imp.drawlines(img0,img1,mkpts0,mkpts1,r'D:\DownloadCache')
    print('RISG matching time: %6.3fs. Matching points num: %d, main diretion: %6.2f' % (
        time.perf_counter() - start_time, conf, main_dir))
    # aff_matrix = cv2.getAffineTransform(mkpts0,mkpts1)
    # dst = cv2.warpAffine(img0,Mat,(0,0))
    # # dst = cv2.warpPerspective(img1, Mat, (0, 0))
    # imp.im_write('d7.jpg',dst,r'D:\python_program\2024\sat-geo-loc')
    # imp.cv_show('1',dst)
    corners = find_corners(r"D:\DownloadCache\1_1681_644_2481_1144_-40.jpgF")
    result = np.dot(Mat,add_ones(corners).T).T[:, 0:2]

    print(result)